<template>
	<el-container>
		<el-aside style="float:left;width: 300px;">
			<el-card class="box-card el-card-flex">
				<!--树状图搜索框 -->
				<div slot="header" class="clearfix">
					<el-input v-model="filterText" placeholder="请搜索" suffix-icon="el-icon-search" clearable></el-input>
				</div>
				<!-- 树状图 -->
				<div class="text item el-over-auto">
					<el-tree v-show="filterText" :ref="filterText?'tree':''" :highlight-current="true" :data="dataTree"
					 default-expand-all :props="defaultProps" node-key="nodeId" @node-click="handleNodeClick"></el-tree>
					<el-tree v-show="!filterText" :ref="!filterText?'tree':''" :default-expanded-keys="treeExpandedKey"
					 :highlight-current="true" :load="loadNode" :props="defaultProps" node-key="nodeId" lazy @node-click="handleNodeClick"
					 :key="keyTree"></el-tree>
				</div>
			</el-card>
		</el-aside>
		<el-main style="padding:0 0 0 10px;">
			<el-card class="box-card el-card-flex">
				<div slot="header" class="clearfix">
					<span>
						<i class="el-icon-menu"></i>
						{{title}}
					</span>
					<el-button style="float: right;margin-left: 10px;" type="danger" plain @click="delEvent" v-show="!application">
						删除
						<i class="el-icon-delete"></i>
					</el-button>
					<el-button style="float: right;" type="info" v-show="!showForm && !application" plain @click="hideButton">
						取消
						<i class="el-icon-refresh-left"></i>
					</el-button>
					<el-button style="float: right;" type="primary" v-show="!showForm && !application" @click="saveEditForm('editForm')"
					 plain>
						保存
						<i class="el-icon-document-checked"></i>
					</el-button>
					<el-button style="float: right;" type="primary" plain @click="showButton" v-show="showForm && !application">
						编辑
						<i class="el-icon-edit"></i>
					</el-button>
					<el-button v-show="currentNodeType != '按钮'" style="float: right;" @click="openAdd" type="primary" plain>
						新增
						<i class="el-icon-plus"></i>
					</el-button>
				</div>
				<!-- 右侧表单 -->
				<div class="text item el-over-auto" style="padding:10px 50px" v-show="!showForm && !application">
					<el-form label-width="100px" :model='editForm' ref='editForm'>
						<el-form-item label="节点编码" prop="nodeCode">
							<el-col :span="12">
								<el-input placeholder="请输入节点编码" v-model="editForm.nodeCode" readonly></el-input>
							</el-col>
						</el-form-item>
						<el-form-item label="节点名称" prop="nodeName" :rules="{ required: true, message: '请输入节点名称' }">
							<el-col :span="12">
								<el-input placeholder="请输入节点名称" v-model="editForm.nodeName"></el-input>
							</el-col>
						</el-form-item>
						<el-form-item label="节点类型" prop="nodeType">
							<el-col :span="10">
								<el-input readonly v-model="editForm.nodeTypeName"></el-input>
							</el-col>
						</el-form-item>
						<el-form-item label="启用状态" prop="enabled">
							<el-col :span="12">
								<el-switch v-model="editForm.enabled" active-value="Y" inactive-value="N"></el-switch>
							</el-col>
						</el-form-item>
						<el-form-item label="排序" prop="sortNo">
							<el-col :span="12">
								<el-input-number v-model="editForm.sortNo"></el-input-number>
							</el-col>
						</el-form-item>
						<el-form-item label="访问地址" prop="nodeUrl" :rules="{ required: true, message: '请输入访问地址' }" v-if="editForm.nodeTypeName=='功能'">
							<el-col :span="12">
								<el-input placeholder="请输入访问地址" v-model="editForm.nodeUrl"></el-input>
							</el-col>
							<el-col :span="12" style="padding-left: 10px;">
								<el-checkbox border true-label="/layout" false-label="" v-model="editForm.layout">顶部导航</el-checkbox>
								<el-checkbox border true-label="/frame" false-label="" v-model="editForm.frame">侧边导航</el-checkbox>
							</el-col>
						</el-form-item>
						<el-form-item label="普通图标">
							<el-col :span="24" class="upload-no-trans">
								<el-upload list-type="picture-card" :headers="nodeIconUploadHeaders()" :action="fileuploadUrl" :file-list="nodeIconDList"
								  :on-change="nodeIconDUploadChange" :on-remove="nodeIconDRemove"
								 :on-success="nodeIconDUploadSuccess" :on-error="nodeIconUploadError">
									<i slot="default" class="el-icon-plus"></i>
									 <div slot="tip" class="el-upload__tip">图标大小不超过500kb，推荐上传尺寸100px*100px,色值 #909399 的png文件</div>
								</el-upload>
							</el-col>
						</el-form-item>
						<el-form-item label="高亮图标">
							<el-col :span="24" class="upload-no-trans">
								<el-upload list-type="picture-card" :headers="nodeIconUploadHeaders()" :action="fileuploadUrl" :file-list="nodeIconLList" 
								 :on-change="nodeIconLUploadChange" :on-remove="nodeIconLRemove"
								 :on-success="nodeIconLUploadSuccess" :on-error="nodeIconUploadError">
									<i slot="default" class="el-icon-plus"></i>
									<div slot="tip" class="el-upload__tip">图标大小不超过500kb，推荐上传尺寸100px*100px,色值 #409eff 的png文件</div>
								</el-upload>
							</el-col>
						</el-form-item>
						<el-form-item label="说明" prop="nodeDesc">
							<el-col :span="16">
								<el-input type="textarea" :rows="3" placeholder="请输入说明" v-model="editForm.nodeDesc"></el-input>
							</el-col>
						</el-form-item>
					</el-form>
				</div>
				<!-- 应用详情显示视图-->
				<ApplicationForm v-show="application" :appForm="appForm"></ApplicationForm>
				<!-- 菜单功能详情显示视图-->
				<ViewForm v-show="showForm&&!application" :editForm='editForm'></ViewForm>
				<!-- 新增表单-->
				<AddForm :dialogAdd='dialogAdd' :appForm="appForm" :editForm='editForm' :nodeTypeData="nodeTypeData" :refTree="refTree"
				 @addData='addData'></AddForm>
			</el-card>
		</el-main>
	</el-container>
</template>

<script>
	import {
		getCookie //获取cookie
	} from '@/api/layout/layout.js'
	import {
		fileuploadUrl, //文件上传接口（无状态）
		attachPath, //附件绝对地址
		uploadByBusinessUrl, //上传接口
		findAttchList, //获取文件列表
		preview, //预览图片
		deleteAttid //附件删除
	} from '@/api/attachCommon/attachCommon.js'
	import {
		getMenuFuncSearch, //查询菜单（节点）
		getAppAuth, //获取顶级节点（应用节点）
		getRootMenuFunc, //获取菜单节点（根据appId）
		getMenuFunChildren, //获取菜单（功能）节点（根据nodeId）
		getCcmsApps, //获取应用详情（根据appId）
		getMenuFuncCont, //获取菜单或功能详情（根据nodeId）
		getNodeType, //获取节点类型
		postMenuFun, //保存节点
		deleteMenuFun, //删除节点
	} from '@/api/authority/menuManage/menuManage.js'
	import {
		Tree,
		Dialog,
		MessageBox,
		Message,
		Upload,
	} from 'element-ui';
	import ApplicationForm from './application.vue';
	import AddForm from './addForm.vue';
	import ViewForm from './viewForm.vue';
	export default {
		components: {
			'el-tree': Tree, //树形菜单
			'el-dialog': Dialog, //对话框
			'el-upload': Upload, //附件
			AddForm, //新增模块
			ViewForm, //展示模块
			ApplicationForm //应用信息详情模块
		},
		data() {
			return {
				fileuploadUrl: fileuploadUrl, //附件上传接口
				nodeIconDList: [], //附件队列（默认图标）
				nodeIconLList:[],//附件队列（高亮图标）
				nodeIconDImg:"",
				filterText: '',
				refTree: {},
				treeExpandedKey: [], //默认展开的树形节点
				keyTree: 1,
				dataTree: [],
				defaultProps: {
					isLeaf: 'isLeaf',
					label: "nodeName"
				},
				editForm: {
					sortNo: "", //排序
					nodeCode: "", //节点编码
					nodeName: "", //节点名称
					nodeType: "", //节点类型
					enabled: "", //启用状态
					nodeUrl: "", //访问地址
					realAddr: "", //补充路径
					layout: "",
					frame: "",
					nodeIcon: "", //图标
					nodeIconD: "", //普通图标
					nodeIconL: "", //高亮图标
					nodeDesc: "" //说明
				},
				appForm: {
					appId: "",
					appCode: "",
					appName: "",
					appStatus: "",
					ipAddr: "",
					ipPort: "",
					appInfo: "",
					appDesc: ""
				},
				title: '应用详情', //详情标题名
				dialogAdd: false,
				showForm: true, //菜单 编辑 展示儿显示初始化
				application: true, //应用详情显示控制
				nodeTypeDataSource: [],
				nodeTypeData: [], //菜单功能类型数据源
				currentNodeType: "" //当前节点类型
			};
		},
		watch: {
			filterText(val) { //树查询
				if (val) {
					getMenuFuncSearch(val).then(res => {
						this.deepChild(res.data.data);
						this.dataTree = res.data.data
					})
				} else {
					this.filterText = ""
					this.keyTree += 1
				}
			}
		},
		methods: {
			/* 图片显示路径转换 */
			nodeIconUrl(url) {
				if (!url){
					return ''
				}
				if (url && url.search('http') < 0) {//绝对路径转换
					url = attachPath + url
				}
				return url
			},
			/* 设置上传附件的请求头（认证信息） */
			nodeIconUploadHeaders() {
				return {
					Authorization: getCookie("Authorization") //认证信息
				}
			},
			/* 文件移除 (普通图标)*/
			nodeIconDRemove(file) {
				this.editForm.nodeIconD=""
			},
			/* 文件移除 (高亮图标)*/
			nodeIconLRemove(file) {
				this.editForm.nodeIconL=""
			},
			/* 附件上传拦截 (普通图标)*/
			nodeIconDUploadChange(file, fileList) { //文件发生改变
				var imageClass = file.name.substring(file.name.lastIndexOf(".") + 1);
				const imageStyle =
					imageClass === "jpg" ||
					imageClass === "JPG" ||
					imageClass === "png" ||
					imageClass === "PNG" ||
					imageClass === "bpm" ||
					imageClass === "BPM" ||
					imageClass === "JPEG" ||
					imageClass === "jpeg";
				if (!imageStyle) {
					Message({
						message: "上传图片只能是jpg / png / bpm/jpeg格式!",
						type: "error"
					});
					fileList.pop()
					this.nodeIconDList = fileList
				} else {
					if(fileList.length>1){
						fileList.splice(0,1)
					}
					this.nodeIconDList = fileList
					return imageStyle
				}
			},
			/* 附件上传拦截 (高亮图标)*/
			nodeIconLUploadChange(file, fileList) { //文件发生改变
				var imageClass = file.name.substring(file.name.lastIndexOf(".") + 1);
				const imageStyle =
					imageClass === "jpg" ||
					imageClass === "JPG" ||
					imageClass === "png" ||
					imageClass === "PNG" ||
					imageClass === "bpm" ||
					imageClass === "BPM" ||
					imageClass === "JPEG" ||
					imageClass === "jpeg";
				if (!imageStyle) {
					Message({
						message: "上传图片只能是jpg / png / bpm/jpeg格式!",
						type: "error"
					});
					fileList.pop()
					this.nodeIconLList = fileList
				} else {
					if(fileList.length>1){
						fileList.splice(0,1)
					}
					this.nodeIconLList = fileList
					return imageStyle
				}
			},
			/* 文件上传(提交)接口成功（普通图标） */
			nodeIconDUploadSuccess(res) {
				if (res.code != 10000) {
					Message.error('上传失败')
					return
				}
				this.editForm.nodeIconD = res.data[0].filePth
			},
			/* 文件上传(提交)接口成功 (高亮图标）)*/
			nodeIconLUploadSuccess(res) {
				if (res.code != 10000) {
					Message.error('上传失败')
					return
				}
				this.editForm.nodeIconL = res.data[0].filePth
			},
			/* 文件上传(提交)接口失败 */
			nodeIconUploadError(err) {
				Message.error('操作失败')
			},
			/* 递归遍历树形数据源 */
			deepChild(val) {
				let $this = this;
				if (val && Array.isArray(val) && val.length) {
					val.forEach(item => {
						if (typeof item === 'object') {
							item.nodeId = item.id;
							item.nodeName = item.name;
							$this.deepChild(item.children);
						}
					});
				}
			},
			loadNode(node, resolve) { //树形图父节点
				if (node.level === 0) {
					getAppAuth().then(res => { //应用树的数据
						let appDatas = res.data.data;
						appDatas.forEach(e => {
							e.isLeaf == "Y" ? e.isLeaf = true : e.isLeaf = false;
							e.nodeName = e.appName;
							e.nodeId = e.appId;
						});
						resolve(appDatas)
						this.title = '应用详情'
						this.$refs.tree.setCurrentKey(appDatas[0].nodeId);
						this.applictionData(appDatas[0].nodeId)
						this.treeExpandedKey = [appDatas[0].nodeId];
					})
				} else if (node.level === 1) {
					getRootMenuFunc(node.data.appId).then(res => {
						res.data.data.forEach(e => {
							e.isLeaf == "Y" ? e.isLeaf = true : e.isLeaf = false;
						});
						this.application = true
						resolve(res.data.data)
						this.title = '应用详情'
					})
				} else {
					getMenuFunChildren(node.data.nodeId).then(res => {
						res.data.data.forEach(e => {
							e.isLeaf == "Y" ? e.isLeaf = true : e.isLeaf = false;
						});
						this.application = false
						this.title = '菜单详情'
						resolve(res.data.data)
					})
				}
			},
			handleNodeClick(data, node) { //点击树形图 获取树点击行数据
				if (data.appName || data.appId == null) {
					this.setAppMode(data); //设置为应用模式
				} else {
					this.setMenuMode(data); //设置为菜单节点模式
				}
			},
			//设置为应用模式
			setAppMode(data) {
				this.applictionData(data.appId) //应用详情
				this.application = true //启用应用视图
				this.showForm = true //关闭编辑视图
				this.title = '应用详情'
				this.currentNodeType = "app"; //按钮节点类型，隐藏新增按钮
			},
			applictionData(appId) { //应用 表单数据获取
				getCcmsApps(appId).then(res => {
					let data = res.data.data;
					this.appForm = data;
					this.nodeTypeData = [];
					this.nodeTypeDataSource.forEach(item => {
						if (item.name == "菜单" || item.name == "功能") {
							this.nodeTypeData.push(item);
						}
					})
				});
			},
			//设置为菜单节点模式
			setMenuMode(data) {
				this.formData(data.nodeId) //菜单详情
				this.showForm = true //关闭编辑视图
				this.application = false //关闭应用视图
				this.title = '菜单详情'
			},
			formData(nodeId) { //菜单 功能 表单数据获取
				getMenuFuncCont(nodeId).then(res => {
					let data = res.data.data;
					let realAddrs = [];
					if (data.realAddr) {
						data.realAddr.split("/").forEach(e => {
							if (e) {
								realAddrs.push("/" + e)
							}
						})
						data.layout = realAddrs[0]
						data.frame = realAddrs[1]
					}
					if(data.nodeIcon){//解析普通图标与高亮图标
						let nodeIcons = data.nodeIcon.split(',')
						data.nodeIconD = nodeIcons[0]?nodeIcons[0]:''
						data.nodeIconL = nodeIcons[1]?nodeIcons[1]:''
					}
					this.editForm = data
					this.currentNodeType = this.editForm.nodeTypeName; //按钮节点类型，隐藏新增按钮
					if (data.nodeType == "d04194db50a745beabf012e36fce19dd" || data.nodeTypeName == "菜单") { //如果是菜单
						this.nodeTypeData = [];
						this.nodeTypeDataSource.forEach(item => {
							if (item.name == "菜单" || item.name == "功能") {
								this.nodeTypeData.push(item);
							}
						})
					} else if (data.nodeType == "fb5c03b5e524455888c4eb52cbcf1baa" || data.nodeTypeName == "功能") {
						this.nodeTypeData = [];
						this.nodeTypeDataSource.forEach(item => {
							if (item.name == "按钮") {
								this.nodeTypeData.push(item);
							}
						})
					}
				})
			},
			showButton() { //编辑按钮事件
				this.showForm = false
				this.nodeIconDList.splice(0,this.nodeIconDList.length)
				if(this.editForm.nodeIconD){
					this.nodeIconDList.push({
						name:'',
						url:this.nodeIconUrl(this.editForm.nodeIconD)
					})
				}
				this.nodeIconLList.splice(0,this.nodeIconLList.length)
				if(this.editForm.nodeIconL){
					this.nodeIconLList.push({
						name:'',
						url:this.nodeIconUrl(this.editForm.nodeIconL)
					})
				}
			},
			renderNodeType() { //节点类型数据源
				getNodeType().then(res => {
					if (res.data.code != 10000) return;
					this.nodeTypeDataSource = res.data.data;
					this.nodeTypeData = [];
					this.nodeTypeDataSource.forEach(item => {
						if (item.name == "菜单") {
							this.nodeTypeData.push(item);
						}
					})
				})
			},
			saveEditForm(formName) { //保存按钮事件
				this.$refs[formName].validate((valid) => {
					if (valid) {
						this.editForm.realAddr = "";
						if (this.editForm.layout) {
							this.editForm.realAddr += this.editForm.layout
						}
						if (this.editForm.frame) {
							this.editForm.realAddr += this.editForm.frame
						}
						this.editForm.nodeIcon = ""
						if(this.editForm.nodeIconD){//普通图标
							this.editForm.nodeIcon += this.editForm.nodeIconD
						}
						if(this.editForm.nodeIconL){//高亮图标
							this.editForm.nodeIcon += ','+this.editForm.nodeIconL
						}
						postMenuFun(this.editForm).then(res => {
							if (res.data.code == 10000) {
								Object.assign(this.$refs.tree.getCurrentNode(), this.editForm) //更新树节点
								this.showForm = true
								Message({
									type: 'success',
									message: "保存成功"
								})
							}
						})
					}
				});
			},
			hideButton() { //取消按钮事件
				this.showForm = true
				let data = this.$refs.tree.getCurrentNode()
				if (data.appName || data.appId == null) {
					this.setAppMode(data); //设置为应用模式
				} else {
					this.setMenuMode(data); //设置为菜单节点模式
				}
			},
			openAdd() { //新增按钮事件
				this.dialogAdd = true
			},
			addData(a, data) {
				this.dialogAdd = a
				if (data) {
					let pData = this.$refs.tree.getCurrentNode(); //获取要新增的父节点id
					let pNode = this.$refs.tree.getNode(pData);
					if (pNode.isLeaf) { //如果是叶子节点
						pNode.isLeaf = false;
						pNode.isLeafByUser = false; //设置为非叶子节点
						pNode.loaded = true; //设置为已加载状态
						pNode.expanded = true; //设置父节点展开
					}
					data.isLeaf = true;
					this.$refs.tree.append(data, pData.nodeId); //手动插入树节点，不刷新树
				}
			},
			delEvent() { //删除按钮事件
				MessageBox.confirm('您确定删除当前选中的菜单吗？').then(() => {
					let cData = this.$refs.tree.getCurrentNode();
					let nId = cData.nodeId
					deleteMenuFun(nId).then(res => {
						if (res.data.code == 10000) {
							Message({
								type: 'success',
								message: '删除成功'
							});
							if (cData.upNodeId == -1) { //如果是顶级菜单节点
								this.$refs.tree.remove(nId);
								this.$refs.tree.setCurrentKey(cData.appId); //删除后默认选中父节点
								this.setAppMode(cData)
							} else { //如果是菜单功能节点
								this.$refs.tree.remove(nId);
								this.$refs.tree.setCurrentKey(cData.upNodeId); //删除后默认选中父节点
								this.formData(cData.upNodeId) //菜单详情
							}
						}
					})
				})
			}
		},
		mounted() {
			this.renderNodeType() //获取节点类型数据源
			this.refTree = this.$refs.tree;
		}
	};
</script>
